package net.hn.hnms.biz.analysis.utils;

import net.hn.hnms.biz.analysis.domain.dto.SensorStatusDto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataJudgeUtil {

    /**
     * 创建时间字典
     *
     * @param beginTime      起始时间 (格式：yyyy-MM-dd HH:mm:ss)
     * @param endTime        结束时间 (格式：yyyy-MM-dd HH:mm:ss)
     * @param sTime          初始时间 (格式：yyyy-MM-dd HH:mm:ss)
     * @param minuteInterval 时间间隔（分钟）
     * @return 时间字典，键为起始时间，值为结束时间
     */
    public static Map<String, String> createTimeDict(String beginTime, String endTime, String sTime, int minuteInterval) {
        Map<String, String> dateDict = new HashMap<>();

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析输入时间
        LocalDateTime dateStart = LocalDateTime.parse(beginTime, formatter);
        LocalDateTime dateEnd = LocalDateTime.parse(endTime, formatter);
        LocalDateTime tempDate = LocalDateTime.parse(sTime, formatter);

        // 初始化字典
        dateDict.put(beginTime, sTime);

        // 循环生成时间区间
        while (!dateStart.isAfter(dateEnd) && !tempDate.isAfter(dateEnd)) {
            // 增加时间间隔
            dateStart = dateStart.plusMinutes(minuteInterval);
            tempDate = tempDate.plusMinutes(minuteInterval);

            // 格式化时间
            String bTime = dateStart.format(formatter);
            String eTime = tempDate.format(formatter);

            // 添加到字典
            if (!dateStart.isAfter(dateEnd) && !tempDate.isAfter(dateEnd)) {
                dateDict.put(bTime, eTime);
            }
        }

        return dateDict;
    }

    public static String getAlarmType(double increaseRate) {
        String alarmType = "5"; // 默认报警类型

        if (increaseRate >= 0.2 && increaseRate < 0.3) {
            alarmType = "0";
        } else if (increaseRate >= 0.3 && increaseRate < 0.4) {
            alarmType = "1";
        } else if (increaseRate >= 0.4 && increaseRate < 0.5) {
            alarmType = "2";
        } else if (increaseRate >= 0.5) {
            alarmType = "3";
        }

        return alarmType;
    }


    public static List<List<SensorStatusDto>> createSensorInfos(String sensors) {
        List<List<SensorStatusDto>> result = new ArrayList<>();

        // 如果输入为空，直接返回 null
        if (sensors == null || sensors.isEmpty()) {
            return null;
        }

        // 如果包含 '$'，按 '$' 分割
        if (sensors.contains("$")) {
            String[] temp = sensors.split("\\$");
            for (String item : temp) {
                List<SensorStatusDto> tempList = processSensorGroup(item);
                result.add(tempList);
            }
        } else {
            // 如果不包含 '$'，直接处理整个字符串
            List<SensorStatusDto> tempList = processSensorGroup(sensors);
            result.add(tempList);
        }

        // 为每个传感器组生成 MD5 键
        for (List<SensorStatusDto> item : result) {
            List<String> sensorList = new ArrayList<>();
            for (SensorStatusDto sensor : item) {
                String deviceCategory = sensor.getDeviceCategory();
                sensorList.add(deviceCategory);
            }
            String md5Key = generateMd5Hashcode(java.lang.String.join(",", sensorList));
            for (SensorStatusDto sensor : item) {
                sensor.setMd5Key(md5Key);
            }
        }

        return result;
    }

    public static String generateMd5Hashcode(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            byte[] digest = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    private static List<SensorStatusDto> processSensorGroup(String sensorGroup) {
        List<SensorStatusDto> tempList = new ArrayList<>();
        String[] tempSensorList = sensorGroup.split("!");
        for (String item : tempSensorList) {
            String[] sensorParts = item.split("\\^");
            String tableName = sensorParts[0];
            String[] sensorAttrs = sensorParts[1].split("~");

            SensorStatusDto sensorStatus = new SensorStatusDto();
            sensorStatus.setTableName(tableName);
            sensorStatus.setDeviceCategory(sensorAttrs[0]);
            sensorStatus.setDeviceSequenceNumber(sensorAttrs[1]);
            sensorStatus.setDeviceName(sensorAttrs[2]);
            sensorStatus.setSensorTag(sensorAttrs[3]);
            sensorStatus.setStartFlag(Integer.parseInt(sensorAttrs[4]));
            sensorStatus.setStopFlag(Integer.parseInt(sensorAttrs[5]));
            tempList.add(sensorStatus);
        }
        return tempList;
    }

}
